import UIKit
/**
    B站：https://www.bilibili.com/video/BV144411C7Gg?p=43

    第43课 无主引用 unowned
 
 
 和 weak 有什么区别呢？

 */

class LangLua {
    var ref: LangJava? = nil
    var name: String
    init(name: String) {
        self.name = name
    }
    
    deinit {
        print("LangLua 内存被释放了 -", self.name)
    }
}

class LangJava {
    var ref: LangLua
    var name: String
    init(name: String, ref: LangLua) {
        self.name = name
        self.ref = ref
    }
    
    deinit {
        print("LangJava 内存被释放了 -", self.name)
    }
}

var obj3: LangLua? = LangLua(name: "Lua")
obj3?.ref = LangJava(name: "Java", ref: obj3!)

// obj3 和 obj4 形成了循环引用
obj3?.ref = nil
obj3 = nil
// 为什么 -----  2步 就可以了？？？？？？？？？
//  就因为 LangJava 的 ref 不是可选类型？
//  1    obj3?.ref = LangJava(name: "Java", ref: obj3!)  -- 引用计数为1
//  2    obj3?.ref = nil; -- LangJava 引用计数就为 0 了
//  说明，还真是 需要 可选类型，才能让 LanJava 的引用计数清零







class LangGo {
    var ref: LangPython? = nil
    var name: String
    init(name: String) {
        self.name = name
    }
    
    deinit {
        print("  LangGo 内存被释放了 -", self.name)
    }
}

class LangPython {
    unowned var ref: LangGo
    var name: String
    init(name: String, ref: LangGo) {
        self.name = name
        self.ref = ref
    }
    
    deinit {
        print("  LangPython 内存被释放了 -", self.name)
    }
}

var obj4: LangGo? = LangGo(name: "Go")
obj4?.ref = LangPython(name: "Python", ref: obj4!)

obj4 = nil
